<template>
  <div>
    <GoodsTop @search='searchFn'>
      <template>
        商品搜索：
      </template><!-- 插槽 -->
    </GoodsTop>
    <!-- 列表区域 -->
    <div class="list">
      <el-button
        type="warning"
        @click="addFn"
      ><i class="el-icon-circle-plus-outline"></i>新建</el-button>
      <el-button
        type="warning"
        plain
        class="enterbtn"
        @click="enterFn"
      > <span class="enter">导入数据</span> </el-button>
      <el-table
        :data="classList"
        style="width: 100%"
        size='medium'
      >
        <el-table-column
          type="index"
          :index='indexAdd'
          label="序号"
          width="100"
        >
          <!--  type="index" :index="indexMethod" element表单中的方法 -->

        </el-table-column>
        <el-table-column
          prop="skuName"
          label="商品名称"
          width="150px"
        >
        </el-table-column>
        <!-- ---------------- -->
        <el-table-column
          prop="skuImage"
          label="商品图片"
        >
          <template slot-scope="scope">
            <img
              :src="classList[scope.$index].skuImage"
              alt=""
              class="sku-image"
            >
          </template>

        </el-table-column>

        <el-table-column
          prop="brandName"
          label="品牌"
        >
        </el-table-column>
        <el-table-column
          prop="unit"
          label="规格"
        >
        </el-table-column>
        <el-table-column
          prop="price"
          label="商品价格"
        >
        </el-table-column>
        <el-table-column
          prop="skuClass.className"
          label="商品类型"
        >
        </el-table-column>

        <el-table-column
          prop="createTime"
          label="创建日期"
          width="160px"
        >
        </el-table-column>

        <!-- ---------------- -->
        <!-- 操作 -->
        <el-table-column
          fixed="right"
          label="操作"
          width="90px"
        >
          <template v-slot={row}>
            <el-link
              type="primary"
              @click="putFn(row)"
            >修改</el-link>

          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="page">
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page="currentPage1"
          layout="slot,next,prev"
          prev-text='上一页'
          next-text='下一页'
          :total="totalCount "
        >
          <template>
            <span class="num-txt">
              共{{totalCount}}条记录
              第{{currentPage1}}/{{totalPage}}页
            </span>
          </template>
          <!--  @current-change 当前页变动时触发的事件 -->
        </el-pagination>
      </div>

      <!--新增对话框 -->
    </div>
    <el-dialog
      :title="flag ? '新增商品' :'修改商品'"
      :visible.sync="dialogFormVisible"
    >
      <el-form
        :model="form"
        :rules="rules"
        ref='addForm'
      >
        <el-form-item
          label="商品名称:"
          :label-width="formLabelWidth"
          prop="skuName"
        >
          <el-input
            type="text"
            placeholder="请输入"
            v-model="form.skuName"
            maxlength="15"
            show-word-limit
          >
          </el-input>
        </el-form-item>

        <el-form-item
          label="品牌:"
          :label-width="formLabelWidth"
          prop="brandName"
        >
          <el-input
            type="text"
            placeholder="请输入"
            v-model="form.brandName"
            maxlength="10"
            show-word-limit
          >
          </el-input>
        </el-form-item>
        <el-form-item
          label="商品价格(元):"
          :label-width="formLabelWidth"
          prop="price"
        >
          <el-input
            type="text"
            placeholder="请输入"
            v-model="form.price"
          >
            <template #suffix>
              <button
                class="el-icon-arrow-up"
                @click="addFFn"
              ></button>
              <button
                class="el-icon-arrow-down"
                @click="subFFn"
              ></button>

            </template>
          </el-input>

        </el-form-item>
        <el-form-item
          label="商品类型:"
          :label-width="formLabelWidth"
          prop="skuClass.className"
        >
          <el-select
            v-model="form.skuClass.className"
            placeholder="请选择"
          >
            <el-option
              v-for="item in optionsList"
              :key="item?.className"
              :value="item?.className"
            >
           <!--  :label="item.className" -->
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="规格:"
          :label-width="formLabelWidth"
          prop="unit"
        >
          <el-input
            type="text"
            placeholder="请输入"
            v-model="form.unit"
            maxlength="10"
            show-word-limit
          >
          </el-input>
        </el-form-item>
        <el-form-item
          label="商品图片:"
          :label-width="formLabelWidth"
          prop="skuImage"
        >

          <!-- 新建上传图片 -->
          <el-upload
            class="avatar-uploader"
            action="https://likede2-admin.itheima.net/likede/api/vm-service/sku/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess1"
            :before-upload="beforeAvatarUpload1"
            name='fileName'
            :headers="myHeaders"
          >
            <img
              v-if="imageUrl"
              :src="imageUrl"
              class="avatar"
            >
            <i
              v-else
              class="el-icon-plus avatar-uploader-icon"
            ></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          @click="dialogFormVisible = false"
          type="warning"
          plain
        >取 消</el-button>
        <el-button
          type="warning"
          @click="submit"
        >确 认</el-button>
      </div>
    </el-dialog>
    <!-- 数据导入弹框 -->
    <el-dialog
      title="数据导入"
      :visible="dialogFormVisible1"
    >
      <el-form ref='addForm'>
        <el-form-item
          label="标题:"
          :label-width="formLabelWidth"
        >
          <el-upload
            class="upload-demo"
            action="https://likede2-admin.itheima.net/likede/api/vm-service/sku/upload"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :show-file-list='false'
            name='fileName'
            :headers="myHeaders"
          >
            <el-button
              size="small"
              type="primary"
            >上传文件</el-button>
            <div
              slot="tip"
              class="el-upload__tip"
            >
              支持扩展名：xls、xlsx，文件不得大于1M
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          @click="dialogFormVisible1 = false"
          type="warning"
          plain
        >取 消</el-button>
        <el-button
          type="warning"
          @click="dialogFormVisible1 = false"
        >确 认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import GoodsTop from '@/components/goodstop.vue'

import { addGoods, goodsearch, putGoods, GoodsSearch } from '@/api/goods'
import { getToken } from '@/utils/storage'
export default {
  name: 'GoodsManage',
  components: {
    GoodsTop

  },
  async created () {
    // 商品类型
    this.handleCurrentChange()// 当前页变动时触发
  },
  methods: {
    /* 新建图片 */
    handleAvatarSuccess1 (file) {
      console.log(file)
      this.imageUrl = file
      this.form.skuImage = file
      this.$message.success('上传成功')
    },
    beforeAvatarUpload1 (file) {
      const isJPG = file.type === 'image/jpeg' || 'image/png'
      const isLt100kb = file.size / 1024 / 1024 < 0.1// 100kb

      if (!isJPG) {
        this.$message.error('图片只能是 JPG 或者PNG格式!')
      }
      if (!isLt100kb) {
        this.$message.error('图片大小不能超过 100kB!')
      }
      return isJPG && isLt100kb
    },
    /* ---------------导入数据--------------------- */
    handleAvatarSuccess () {
      this.$message.success('上传成功')
    },
    // 限制文件上传大小
    beforeAvatarUpload (file) {
      const isLt1M = file.size / 1024 / 1024 < 1
      if (!isLt1M) {
        this.$message.error('上传文件大小不能超过 1MB!')
        return false
      }

      // 判断文件类型来筛选文件格式上传
      if (
        !file.name.endsWith('.xlsx' || 'xls')
      ) {
        this.$message.error('上传格式不正确，请重新上传!')
        return false
      }
      return this.$message.success('上传成功')
    },
    // 加加减减
    addFFn () {
      this.form.price += 0.5
    },
    subFFn () {
      if (this.form.price >= 0.5) {
        this.form.price -= 0.5
      }
    },
    async handleCurrentChange (val = 1) {
      const res1 = await goodsearch({ pageIndex: val, pageSize: this.pageSize })
      console.log(res1)

      this.classList = res1.data?.currentPageRecords.map(item => {
        return { // 渲染的页面信息
          brandName: item.brandName,
          createTime: this.$moment(item.createTime).format('YYYY.MM.DD HH:mm:ss'),
          price: item.price,
          skuImage: item.skuImage,
          skuName: item.skuName,
          unit: item.unit,
          skuId: item.skuId,
          classId: item.classId,
          skuClass: {
            className: item?.skuClass?.className,
            classId: item?.skuClass?.classId
          }
        }
      })
      // this.id = this.classList.map(item => item.skuClass.classId)
      this.totalPage = res1.data.totalPage
      // console.log(this.classList[0].createTime);
      console.log(this.totalPage)
      this.currentPage1 = val
      this.totalCount = Number(res1.data.totalCount)// 转化成数字
      console.log(`当前页: ${val}`)
    },
    // 序号
    indexAdd (index) {
      return this.pageSize * (this.currentPage1 - 1) + index + 1
    },
    // 查询
    async searchFn (input) {
      const res = await goodsearch({ pageIndex: 1, pageSize: 10000 })
      console.log(res)
      input ? this.classList = res.data.currentPageRecords.filter(item => item.skuName === input) : this.handleCurrentChange()
      this.classList = this.classList.map(item => {
        return { // 渲染的页面信息
          brandName: item.brandName,
          createTime: this.$moment(item.createTime).format('YYYY.MM.DD HH:mm:ss'),
          price: item.price,
          skuImage: item.skuImage,
          skuName: item.skuName,
          unit: item.unit,
          skuId: item.skuId,
          skuClass: {
            className: item?.skuClass?.className,
            classId: item?.skuClass?.classId
          }
        }
      })
    },
    // 新增确认
    async submit () {
      //  await this.$refs.form.validate()
      if (this.flag === true) {
        /*  let formData = this.form
          delete formData?.skuClass
          delete formData?.skuId
          console.log(formData); */
        await addGoods({
          skuName: this.form.skuName,
          skuImage: this.form.skuImage,
          price: this.form.price,
          brandName: this.form.brandName,
          unit: this.form.unit,
          classId: this.form.classId
        })
      } else {
        await putGoods(
          {
            skuName: this.form.skuName,
            skuImage: this.form.skuImage,
            price: this.form.price,
            brandName: this.form.brandName,
            unit: this.form.unit,
            classId: this.form.classId,
            skuId: this.form.skuId
          }
        )
      }
      this.handleCurrentChange()
      this.$refs.addForm.resetFields()// 重置表单和校验
      this.dialogFormVisible = false
    },
    // 新建
    async addFn () {
      this.dialogFormVisible = true
      this.flag = true
      const res = await GoodsSearch({ pageIndex: 1, pageSize: 10000 })
      console.log(res)
      this.optionsList = res.data.currentPageRecords// 商品类型选择
    },
    // 修改
    putFn (row) {
      this.dialogFormVisible = true
      this.flag = false
      this.form = { ...row }
      this.imageUrl = row.skuImage// 图片处理
      console.log(this.form)
    },
    // 导入
    enterFn () {
      this.dialogFormVisible1 = true
    }
  },
  data () {
    return {
      // 上传图片
      imageUrl: '',

      // 数据导入
      myHeaders: {
        Authorization: getToken()
      },

      /* --------商品类型选择------------- */
      optionsList: [],
      /* options: [{
          value: '选项1',
          label: ''
        }] */
      value: '',
      input: 0,
      /* ------------------------ */
      currentPage1: 1, // 当前页
      pageSize: 10,
      totalPage: 0,
      totalCount: 0, // 期待是一个数字
      flag: false,
      time: '',

      classList: [
        { // 渲染的页面信息
          brandName: '',
          createTime: '',
          price: 0,
          skuImage: '',
          skuName: '',
          unit: '',
          skuClass: {
            className: '', // 商品类型
            classId: 0
          }

        }],
      // id: 0,//classId
      dialogVisible: false,
      dialogFormVisible1: false, // 导入弹框
      /* 新增 */
      form: {
        skuId: 0,
        skuName: '',
        brandName: '',
        price: 0,
        unit: '',
        classId: 0,
        skuImage: '',
        skuClass: {
          classId: 0,
          className: ''
        }
      },
      rules: {
        skuName: [
          { required: true, message: '请输入', trigger: 'blur' }

        ],
        brandName: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        unit: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        skuImage: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        'skuClass.className': [
          { required: true, message: '请输入', trigger: 'blur' }
        ]
      },
      text: '',
      dialogFormVisible: false,
      formLabelWidth: '120px'
    }
  }
}

</script>

<style lang='less' scoped>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .el-button--small {
    padding: 9px 45px;
    font-size: 11px;
    border-radius: 3px;
    width: 254px;
    margin-left: 17px;
    height: 40px;
  }
  .avatar-uploader-icon[data-v-442fa691] {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
    border: 1px solid #ccc;
}
  .el-upload {
    display: inline-block;
    text-align: center;
    cursor: pointer;
    outline: none;
  }
  .el-upload__tip {
    font-size: 15px;
    color: #bac0cd;
    line-height: 20px;
    margin-left: 12px;
  }
  ::v-deep .svg-icon.svg-fill {
    color: #fff;
  }
  .enterbtn {
    font-size: 18px;
  }
  .enter {
    font-size: 15px;
  }
  ::v-deep .el-upload-dragger {
    background-color: #fff;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    box-sizing: border-box;
    width: 116px;
    height: 106px;
    text-align: center;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  ::v-deep .el-input__suffix-inner {
    pointer-events: all;
    display: flex;
    flex-direction: column;
  }
    ::v-deep [data-v-442fa691] .el-input__suffix {
    position: absolute;
    height: 100%;
    right: 0px;
    top: 0;
    text-align: center;
    color: #fff;
    transition: all 0.3s;
    pointer-events: none;
    width: 47px;
}
  ::v-deep .el-input .el-input__count .el-input__count-inner {
    background: #ffffff;
    line-height: 40px;
    display: inline-block;
    padding: 0 0px;
    height: 0px;
  }
  ::v-deep .el-input__suffix {
    position: absolute;
    height: 100%;
    right: 0px;
    top: 0;
    text-align: center;
    color: #fff;
    transition: all 0.3s;
    pointer-events: none;
    width: 30px;
  }
  ::v-deep .el-select > .el-input {
    display: block;
    width: 398px;
  }
  .el-upload-dragger {
    width: 96px;
    height: 94px;
  }
  .el-upload-dragger .el-icon-upload {
    line-height: 14px;
  }
  // ::v-deep .el-table_2_column_11.el-table__cell{
  //   width: 100x;
  // }
  .el-table_1_column_3 .el-table__cell {
    box-sizing: border-box;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: normal;
    word-break: break-all;
    line-height: 23px;
    padding-left: 10px;
    padding-right: 10px;
  }
  ::v-deep .sku-image {
    display: block;
    width: 24px;
    height: 24px;
    -o-object-fit: cover;
    object-fit: cover;
    border-radius: 50%;
    background: #f3f6fb;
    border: 1px solid #f3f6fb;
  }
  .el-table__body {
    font-size: 14px;
  }
  .num-txt {
    font-size: 16px !important;
    color: #dbdfe5 !important;
    font-weight: 400;
  }
  ::v-deep .el-pagination .btn-prev,
  ::v-deep .el-pagination .btn-next {
    width: 60px;
    height: 32px;
    margin: 0 16px;
    border-radius: 2px;
    background-color: #d5ddf8;
    color: #606266;
    float: right;
  }
  ::v-deep .el-pagination .btn-prev {
    float: right;
  }
  ::v-deep .el-dialog__footer {
    text-align: center;
  }
  .el-form-item__label {
    margin-right: 25px;
    font-size: 15px;
  }
  .el-input {
    width: 400px;
    height: 38px;
  }

  .page {
    width: 1100px;
    // display: flex;
    justify-content: space-between;
    position: absolute;
    bottom: 0;
    left: 0;
    background: #fff;
    padding: 40px 16px;
    margin-left: 20px;
    margin-right: 40px;
  }
  // ::v-deep.el-table__header-wrapper{
  //   background-color: #f3f6fb;
  // }
  .el-button.el-button--warning {
    margin-bottom: 10px;
    margin-right: 28px;
  }
  .list {
    position: relative;
    height: 860px;
    background-color: #fff;
    padding: 25px;
  }

  .search-box.el-button.el-button--primary,
  .list.el-button.el-button--warning {
    width: 60px;
    height: 17px;
    font-size: 16px;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 36px;
    padding: 0;
    /* background-color: #5f84ff; */
    border: none;
    text-align: center;
  }
  .el-icon-circle-plus-outline {
    margin-right: 10px;
    font-size: 19px;
    margin-top: 1px;
  }
  .el-link.el-link--primary {
    margin-right: 10px;
  }
</style>
